package com.koocloud.electroplatemanage.auth.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.koocloud.electroplatemanage.auth.mapper.IPermissionDao;
import com.koocloud.electroplatemanage.auth.mapper.IRoleDao;
import com.koocloud.electroplatemanage.auth.service.IRoleService;
import com.koocloud.electroplatemanage.common.pojo.ResponseTemplate;
import com.koocloud.electroplatemanage.common.util.CommonUtils;
import com.koocloud.electroplatemanage.pojo.Role;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



@Service
public class IRoleServiceimpl implements IRoleService {
	private static Logger log = LoggerFactory.getLogger("auth");
	@Resource
	IRoleDao iRoleDao;
	@Resource
	IPermissionDao iPermissionDao;

	/**
	 * 添加角色
	 */
	@Override
	public Map<String, Object> addRole(Role role) {
		Map<String, Object> map = new HashMap<>();
		List<Map<String, Object>> list=iRoleDao.selectRoleByName(role);
		if (!StringUtils.isEmpty(list) && list.size()>0) {
			map.put("code", 1);
			map.put("message", "已存在该角色");
		}else {
			Integer num = iRoleDao.addRole(role);
			if (num>0) {
				map.put("code", 0);
			} else {
				map.put("code", 1);
				map.put("message", "添加角色异常");
			}
		}
		return map;
	}

	/**
	 * 编辑角色
	 */
	@Override
	public Integer updateRole(String id, String roleName,String remarks) {
		// 根据角色id进行修改角色
		Integer num = iRoleDao.updateRole(id, roleName,remarks);
		return num;
	}

	/**
	 * 删除角色
	 */
	@Override
	public Integer deleteRole(String id) {
		// 根据角色id删除角色
		Integer num = iRoleDao.deleteRole(id);
		return num;
	}

	/**
	 * 获取角色列表
	 */
	@Override
	public List<Role> selectRoleList() {
		List<Role> list = iRoleDao.selectRoleList();
		for (Role role : list) {
	        String hasAuthList = iPermissionDao.selectAllPermissionStrByRoleId(role.getId());
	        role.setHasAuthList(hasAuthList);
        }
		return list;
	}

	/**
	 * 查询根据角色名获取角色信息 角色名不传的话就是查询全部角色
	 */
	@Override
	public List<Map<String, Object>> selectRole(String id, String roleName) {
		List<Map<String, Object>> list = iRoleDao.selectRole(id, roleName);
		return list;
	}
    public ResponseTemplate selectRoleFenye(String id, String roleName, int page, int limit){
		PageHelper.startPage(page, limit, true);
		List<Map<String, Object>> list = iRoleDao.selectRole(id, roleName);
		PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(list);
		return ResponseTemplate.builder().code(0).count((Long) pageInfo.getTotal()).message("").data(pageInfo.getList()).build();
	}
	/**
	 * 分配权限列表（弃用）
	 */
	@Override
	public Map<String, Object> insertAuthList(String id, String hasAuthList2) {
		String hasAuthList = hasAuthList2.replace(" ", "");
		Map<String, Object> map = new HashMap<>();
		// 根据hasRoleList获取对应的role_id
		ArrayList<String> list = new ArrayList<>();
		System.out.println("list之前是否为空:" + list.isEmpty());
		System.out.println("list之前的size大小:" + list.size());
		String[] split = null;
		if (hasAuthList.contains(",")) {
			split = hasAuthList.split(",");
			for (String AuthName : split) {
				String authRemarksId = iPermissionDao.selectRemarksId(AuthName);
				if (!StringUtils.isEmpty(authRemarksId)) {
					list.add(authRemarksId);
				}
			}
		} else {
			// 根据角色名查询对应的权限
			String authRemarksId = iPermissionDao.selectRemarksId(hasAuthList2);
			if (!StringUtils.isEmpty(authRemarksId)) {
				list.add(authRemarksId);
			}

		}
		System.out.println("最后的list,权限集合为:" + list);
		// 根据角色id删除之前的角色权限之间的关系
		iPermissionDao.deleteRoleAuthRelation(id);
		// 根据角色id重新建立角色权限之间的关系
		System.out.println("list之后是否为空:" + list.isEmpty());
		System.out.println("list之后的size大小:" + list.size());
		if (!list.isEmpty()) {
			for (String authid : list) {
				String ids = CommonUtils.resultId();
				iPermissionDao.insert(ids, id, authid);
			}
		}
		map.put("code", 1);
		return map;
	}

	/**
	 * 根据角色添加权限 此处传的是菜单的id集合
	 */
	@Override
	public Map<String, Object> insertRoleAuthList(Role role) {
		Map<String, Object> map = new HashMap<>();
		try { 
			// 判断roleName存不存在
			Integer num = iRoleDao.selectRoleByRoleName(role);
			if (num > 0) {// 数据库已存在该角色
				map.put("code", 1);
				map.put("msg", "已存在该角色,请重新添加");
			} else {// 不存在该角色
				iRoleDao.addRole(role);
				long id = role.getId();// 添加后返回的id
				// 添加完后给该角色赋权
				String[] split = null;
				String hasAuthList = role.getHasAuthList();
				if (hasAuthList.contains(",")) {
					split = hasAuthList.split(",");
					for (String AuthId : split) {
						iRoleDao.addRolePermission(id, Integer.parseInt(AuthId));
					}
				} else {
					iRoleDao.addRolePermission(id, Integer.parseInt(hasAuthList));
				}
			}
			map.put("code", 0);
		} catch (Exception e) {
			log.info(e.toString());
			map.put("code", 1);
			map.put("msg", e.getMessage());
		}
		return map;
	}

	/**
	 * 根据角色id修改对应的角色权限
	 */
	@Override
	public Map<String, Object> updateRoleAuthList(String id1, String hasAuthList) {
		int id = Integer.parseInt(id1);
		Map<String, Object> map = new HashMap<>();
		try {
			// 根据id判断角色存不存在
			Integer num = iRoleDao.selectRoleByRoleId(id);
			if (num > 0) {// 数据库存在该角色
				// 删除对应角色对应的权限
				iRoleDao.deleteRolePermissionById(id);
				// 删除完后给该角色赋权
				String[] split = null;
				if (hasAuthList.contains(",")) {
					split = hasAuthList.split(",");
					for (String AuthId : split) {
						iRoleDao.addRolePermission(id, Integer.parseInt(AuthId));
					}
				} else {
					iRoleDao.addRolePermission(id, Integer.parseInt(hasAuthList));
				}
			} else {// 不存在该角色
				map.put("code", 1);
				map.put("message", "修改角色并修改分配对应的权限异常");
			}
			map.put("code", 0);
		} catch (Exception e) {
			log.info(e.toString());
			map.put("code", 1);
			map.put("message", "修改角色并修改分配对应的权限异常");
		}
		return map;
	}

	/**
	 * 查询角色信息
	 */
	@Override
	public Role selectRoleInfo(Role role) {
		Role	roleEntity =iRoleDao.selectRoleInfo(role);
		String hasAuthList = iPermissionDao.selectAllPermissionStrByRoleId(roleEntity.getId());
		roleEntity.setHasAuthList(hasAuthList);
		return roleEntity;
	}

	/**
	 * 根据用户id修改分配角色 
	 */
	@Override
	public Map<String, Object> updateUserRoleList(String id1, String hasRoleList) {
		int id = Integer.parseInt(id1);
		Map<String, Object> map = new HashMap<>();
		try {
			// 根据id判断用户存不存在
			Integer num = iRoleDao.selectUserByUserId(id);
			if (num > 0) {// 数据库存在该用户
				// 删除对应用户对应的角色
				iRoleDao.deleteUserRoleById(id);
				// 删除完后给该角色赋权
				String[] split = null;
		if (StringUtils.isEmpty(hasRoleList)) {
			map.put("code", 0);
		}else{
			if (hasRoleList.contains(",")) {
				split = hasRoleList.split(",");
				for (String roleId : split) {
					iRoleDao.addUserRole(id, Integer.parseInt(roleId));
				}
			} else {
				iRoleDao.addUserRole(id, Integer.parseInt(hasRoleList));
			}
		}
			

			} else {// 不存在该角色
				map.put("code", 1);
				map.put("message", "不存在该角色");
			}
			map.put("code", 0);
		} catch (Exception e) {
			log.info(e.toString());
			map.put("code", 1);
			map.put("message", "根据用户id修改分配角色异常");
		}
		return map;
	}

	
    /**
     * 重新添加该角色对应该页面拥有的按钮权限
     */
    @Override
    public Integer addRolePermission(String id, Long chilrdId) {
        // TODO Auto-generated method stub
        return iRoleDao.addRolePermissionTwo(id, chilrdId);
    }

	

}
